<template>
  <div class="diy-body" v-loading="initLoading">
    <div class="diy-tool-wrap">
      <div class="diy-tool-box">
        <template v-for="(item, index) in tools" :key="index">
          <div class="tool-item">
            <div
              class="item-title"
              @click.stop="selectedToolItem(item)"
              :class="item.active ? 'active' : ''"
            >
              <span class="icon icon-you-3"></span>{{ item.title }}
            </div>
            <template v-if="item.active && item.data.length > 0">
              <div class="tool-item-list">
                <template v-for="(items, idx) in item.data" :key="idx">
                  <div
                    class="tool-items"
                    :class="
                      items.only &&
                      $utils.arrayFilterMultiple(
                        diyData.items,
                        'type',
                        items.key
                      ) !== -1
                        ? 'disabled'
                        : ''
                    "
                    @click="onAddItem(items.key, items.only || false)"
                  >
                    <span :class="items.icon"></span>
                    <div class="items-title">{{ items.title }}</div>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </template>
      </div>
    </div>

    <div
      class="diy-tool-page"
      :class="selectedEditor == 'page' ? 'active' : ''"
      @click="onEditer('page')"
    >
      页面设置
    </div>

    <div class="diy-preview">
      <storeDiyPreview
        :diyData="diyData"
        @onEditer="onEditer"
        @onDeleleItem="onDeleleItem"
        :selectedIndex="selectedEditor"
      ></storeDiyPreview>
    </div>

    <div class="diy-form-box">
      <div class="diy-save">
        <back-btn v-if="back"></back-btn>
        <el-button type="primary" @click="saveClick" :loading="btnLoading"
          >保存</el-button
        >
      </div>
    </div>

    <div class="diy-editor">
      <template v-if="selectedEditor === 'page'">
        <!-- 编辑器: 页面设置 -->
        <storeDiyEditorPage :diyItem="diyData.page"></storeDiyEditorPage>
      </template>
      <template v-if="diyData.items && diyData.items.length && curDiyItem">

        <template v-if="curDiyItem.type === 'pop_adv'">
          <!-- 编辑器: 弹窗广告 -->
          <storeDiyEditorPopAdv :diyItem="curDiyItem"></storeDiyEditorPopAdv>
        </template>

        <template v-if="curDiyItem.type == 'goods'">
          <!-- 编辑器：商品列表 -->
          <storeDiyEditorGoods
            :diyItem="curDiyItem"
            :opts="opts?.goods_cate"
          ></storeDiyEditorGoods>
        </template>

        <template v-if="curDiyItem.type == 'window'">
          <!-- 编辑器：魔方 -->
          <storeDiyEditorWindow :diyItem="curDiyItem"></storeDiyEditorWindow>
        </template>

        <template v-if="curDiyItem.type == 'single'">
          <!-- 编辑器：单图 -->
          <storeDiyEditorSingle :diyItem="curDiyItem"></storeDiyEditorSingle>
        </template>

        <template v-if="curDiyItem.type == 'banner'">
          <!-- 编辑器：图片轮播 -->
          <storeDiyEditorBanner
            :diyItem="curDiyItem"
            @onEditorAdd="onEditorAddData"
            @onEditorDelele="onEditorDeleleData"
          ></storeDiyEditorBanner>
        </template>

        <template v-if="curDiyItem.type == 'title'">
          <!-- 编辑器：标题栏 -->
          <storeDiyEditorTitle :diyItem="curDiyItem"></storeDiyEditorTitle>
        </template>

        <template v-if="curDiyItem.type == 'notice'">
          <!-- 编辑器：公告 -->
          <storeDiyEditorNotice
            :diyItem="curDiyItem"
            @onEditorAdd="onEditorAddData"
            @onEditorDelele="onEditorDeleleData"
          ></storeDiyEditorNotice>
        </template>

        <template v-if="curDiyItem.type == 'nav_bar'">
          <!-- 编辑器：图文导航 -->
          <storeDiyEditorNavBar
            :diyItem="curDiyItem"
            @onEditorAdd="onEditorAddData"
            @onEditorDelele="onEditorDeleleData"
          ></storeDiyEditorNavBar>
        </template>

        <template v-if="curDiyItem.type == 'search'">
          <!-- 编辑器：搜索 -->
          <storeDiyEditorSearch :diyItem="curDiyItem"></storeDiyEditorSearch>
        </template>

        <template v-if="curDiyItem.type == 'guide'">
          <!-- 编辑器：辅助线 -->
          <storeDiyEditorGuide :diyItem="curDiyItem"></storeDiyEditorGuide>
        </template>

        <template v-if="curDiyItem.type === 'user'">
          <!-- 编辑器: 个人中心 -->
          <storeDiyEditorUser :diyItem="curDiyItem"></storeDiyEditorUser>
        </template>

        <template v-if="curDiyItem.type === 'order'">
          <!-- 编辑器: 我的订单 -->
          <storeDiyEditorOrder :diyItem="curDiyItem"></storeDiyEditorOrder>
        </template>

      </template>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: "storeDiy",
};
</script>
<script  lang="ts" setup >
import { ref, getCurrentInstance, watch, onMounted } from "vue";

import { getDiyPageDefaultData } from "@/api/store/diy_page";
import { diyToolsType, Result, ResultError } from "@/types";

import storeDiyEditorPage from "./editor/default.vue";
import storeDiyEditorPopAdv from "./editor/pop-adv.vue";

import storeDiyEditorGoods from "./editor/goods.vue";

import storeDiyEditorWindow from "./editor/window.vue";
import storeDiyEditorSingle from "./editor/single.vue";
import storeDiyEditorBanner from "./editor/banner.vue";

import storeDiyEditorTitle from "./editor/title.vue";
import storeDiyEditorNotice from "./editor/notice.vue";
import storeDiyEditorNavBar from "./editor/nav-bar.vue";
import storeDiyEditorSearch from "./editor/search.vue";
import storeDiyEditorGuide from "./editor/guide.vue";
import storeDiyEditorUser from "./editor/user.vue";
import storeDiyEditorOrder from "./editor/order.vue";
import storeDiyPreview from "./preview/index.vue";

const props = withDefaults(
  defineProps<{
    modelValue?: any;
    toolsType?: string;
    back?:boolean;
  }>(),
  {
    modelValue: false,
    toolsType: "page",
    back:false,
  }
);

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const selectedToolItem = (item: any) => {
  item.active = !item.active;
};

const selectedEditor = ref<string | number>("page");

// 当前选中的diy元素
const curDiyItem = ref<any>();

/**
 * 编辑当前选中的Diy元素
 */
const onEditer = (index: string | number = "page") => {
  // 记录当前选中元素的索引
  selectedEditor.value = index;
  // 当前选中的元素数据
  if (selectedEditor.value === "page") {
    curDiyItem.value = diyData.value.page;
  } else {
    curDiyItem.value = diyData.value.items[selectedEditor.value];
  }
};

/**
 * 验证新增Diy组件
 */
const onCheckAddItem = (toolKey: string, only: boolean = false) => {
  if (
    only &&
    $utils.arrayFilterMultiple(diyData.value.items, "type", toolKey) !== -1
  ) {
    return false;
  }
  return true;
};

/**
 * 新增Diy组件
 */
const onAddItem = (toolKey: string, only: boolean = false) => {
  // 验证新增Diy组件
  // console.log("新增Diy组件", toolKey);
  if (!onCheckAddItem(toolKey, only)) {
    onEditer($utils.arrayFilterMultiple(diyData.value.items, "type", toolKey));
    return false;
  }
  // 复制默认diy组件数据 避免双向绑定
  let data = JSON.parse(JSON.stringify(defaultItems.value[toolKey]));
  // 新增到diy列表数据
  if (typeof selectedEditor.value == "number") {
    diyData.value.items.splice(selectedEditor.value + 1, 0, data);
    // 编辑当前选中的元素
    onEditer(selectedEditor.value + 1);
  } else {
    diyData.value.items.push(data);
    // 编辑当前选中的元素
    onEditer(diyData.value.items.length - 1);
  }
};

// 初始化编辑器事件
const initEditor = () => {
  onEditer(selectedEditor.value);
};

const initLoading = ref<boolean>(true);

// 默认数据
const defaultItems = ref<any>({});

const diyData = ref<any>({});

// 其他数据
const opts = ref<any>({});

// 工具栏
const tools = ref<diyToolsType>([]);

const toInitDiyData = (isDefault: boolean) => {
  getDiyPageDefaultData({
    tools_type: props.toolsType,
  })
    .then((res: Result) => {
      defaultItems.value = res.data.items;
      opts.value = res.data.opts;
      tools.value = res.data.tools;
      if (isDefault) {
        diyData.value = res.data.data;
      }
      initEditor();
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
      initLoading.value = false;
    });
};

const refreshDiyData = (isDefault: boolean = false, data: any = {}) => {
  diyData.value = data;
  toInitDiyData(isDefault);
};

/**
 * 编辑器：添加data元素
 */
const onEditorAddData = (
  obj: {
    count: number;
    msg: string;
    type: string;
  } = {
    count: -1,
    msg: "",
    type: "",
  }
) => {
  if (obj.count !== -1 && curDiyItem.value.data.length >= obj.count) {
    $utils.errorMsg(obj.msg);
    return false;
  }
  var itemData = {};
  itemData = JSON.parse(
    JSON.stringify(defaultItems.value[obj.type].default_data)
  );
  curDiyItem.value.data.push(itemData);
};

/**
 * 编辑器：删除data元素
 */
const onEditorDeleleData = (obj: { index: number; key: string }) => {
  if (typeof selectedEditor.value == "number") {
    if (diyData.value.items[selectedEditor.value][obj.key].length <= 1) {
      $utils.errorMsg("至少保留一个");
      return false;
    }
    diyData.value.items[selectedEditor.value][obj.key].splice(obj.index, 1);
  } else {
    if (diyData.value[selectedEditor.value][obj.key].length <= 1) {
      $utils.errorMsg("至少保留一个");
      return false;
    }
    diyData.value[selectedEditor.value][obj.key].splice(obj.index, 1);
  }
};

/**
 * 删除diy元素
 * @param index
 */
const onDeleleItem = (index: number | string) => {
  if (index === "float_btn") {
    diyData.value.float_btn.status = 0;
  }
  diyData.value.items.splice(index, 1);
  if (index == 0) index = 1;
  if (typeof index == "number") selectedEditor.value = index - 1;
};

const emit = defineEmits(["save"]);

const btnLoading = ref<boolean>(false);

/**
 * 保存
 */
const saveClick = () => {
  btnLoading.value = true;
  emit("save", diyData.value);
};

const resetBtn = () => {
  btnLoading.value = false;
};

onMounted(() => {});

defineExpose({ initEditor, refreshDiyData, resetBtn });
</script>
<style scoped>
.diy-body {
  position: relative;
  width: 100%;
  height: 100%;
}

.diy-tool-wrap {
  width: 262px;
  height: calc(100% - 42px);
  padding: 20px;
  background: #fff;
  border: 1px solid var(--el-border-color);
  position: absolute;
  top: 0;
  left: 0;
}
.diy-tool-box {
  overflow-x: hidden;
  overflow-y: auto;
}
.diy-tool-wrap .item-title {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 10px;
  width: 100%;
  min-height: 30px;
  line-height: 30px;
  position: relative;
  cursor: pointer;
  user-select: none;
}
.diy-tool-wrap .item-title .icon {
  font-size: 12px;
  margin-right: 10px;
  transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
}
.diy-tool-wrap .tool-item .item-title.active .icon {
  transform: rotate(90deg);
}

.tool-item-list {
  margin: 0 auto;
  padding: 1px;
  width: 100%;
  max-height: 100%;
  vertical-align: baseline;
  transition: all 0.5s;
}
.tool-item-list .tool-items {
  position: relative;
  text-align: center;
  display: inline-block;
  width: calc(33.33% - 8px);
  font-size: 12px;
  margin-right: 4px;
  padding: 10px 0;
  margin-bottom: 8px;
  cursor: pointer;
  vertical-align: baseline;
  background: #f0f0f0;
  border-radius: 2px;
  color: #000;
  user-select: none;
  border: 2px solid #f0f0f0;
}
.tool-item-list .tool-items .icon {
  color: #000;
  font-size: 22px;
  line-height: 40px;
}
.tool-item-list .tool-items:hover {
  color: var(--base-default);
  border: 2px solid var(--base-default);
  background: #fff;
}
.tool-item-list .tool-items:hover .icon {
  color: var(--base-default);
}

.tool-item-list .tool-items.disabled,
.tool-item-list .tool-items.disabled .icon {
  color: #bbb;
  cursor: no-drop;
  background: #f0f0f0;
  border-color: #f0f0f0;
}
/* editor */
.diy-editor {
  width: 406px;
  height: calc(100% - 102px);
  position: absolute;
  padding-bottom: 100px;
  top: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  border: 1px solid var(--el-border-color);
}

.diy-preview {
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  align-items: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  overflow: hidden;
  margin-left: 304px;
  margin-right: 408px;
  height: calc(100% - 60px);
}
.diy-tool-page {
  position: absolute;
  right: 420px;
  top: 0;
  padding: 8px 20px;
  z-index: 3;
  background: #fff;
  user-select: none;
  cursor: pointer;
  z-index: 9;
  box-shadow: 0 2px 8px 0 rgb(0 0 0 / 10%);
  border-radius: 2px;
}
.diy-tool-page:hover,
.diy-tool-page.active {
  background: var(--base-default);
  color: #fff;
}

.diy-form-box {
  position: absolute;
  left: 304px;
  right: 408px;
  bottom: 0;
  display: flex;
  align-items: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>

<style>
.editor-input-block {
  width: 240px;
  line-height: 40px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.editor-input-desc {
  width: 120px;
  font-size: 12px;
  color: var(--base-grey);
}
</style>